package main

import (
	"net"
	"fmt"
	"os"
	"deploy-ms/utils"
)



func handleConnection(tcpcon net.TCPConn) {
	fmt.Println("Client connect")
	data := make([]byte, 1024)

	// receive file name
	wc, err := tcpcon.Read(data)
	file_name := string(data[0:wc])

	// receive file size
	wc, err = tcpcon.Read(data)
	fmt.Println("the file's size is:",utils.BytesToInt64(data[0:wc]))

	fo, err := os.Create(fmt.Sprintf("%s%s", utils.ServerConfig.Get("receive_path").(string),file_name))
	if err != nil {
		fmt.Println("os.Create" + err.Error())
	}

	defer fo.Close()

	for {
		c, err := tcpcon.Read(data)
		if err != nil {
			fmt.Println("tcpcon.Read(data)" + err.Error())
		}
		if string(data[0:c]) == "filerecvend" {
			fmt.Println("string(data[0:c]) == filerecvend is true")
			tcpcon.Write([]byte("file recv finished!\r\n"))
			tcpcon.Close()
			break
		}
		_, err = fo.Write(data[0:c])
		if err != nil {
			fmt.Println("write err" + err.Error())
		}
	}
}
func main() {
	utils.InitServerConfig()
	ip := net.ParseIP(utils.ServerConfig.Get("ip").(string))
	addr := net.TCPAddr{IP: ip, Port: 8888, Zone: ""}
	listener, err := net.ListenTCP("tcp", &addr)
	if err != nil {
		fmt.Println("Initialize error", err.Error())
		return
	}
	for {
		fmt.Println("Server listening...")
		defer listener.Close()
		tcpcon, err := listener.AcceptTCP()
		if err != nil {
			continue
		}
		go handleConnection(*tcpcon)
	}
}

